/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mx.uacam.balam.tracker;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import mx.uacam.balam.entities.Descriptor;
import mx.uacam.balam.entities.SeederDetails;




/**
 *
 * @author User
 */
public class Tracker {
int portClient;
int portSeeder;
//Seder semilla
Descriptor descriptor;
String [] serverAlive;
String host;
ServerSocket  sock;


ObjectOutputStream salida;
ObjectInputStream entrada;
byte [] buffer;


public Descriptor createDescriptor(String fileName, int Status, String addresSeeder, String seederName){


    return descriptor;
}


public void SendDescriptor(String address, int port , Descriptor descriptor){

}

    private void esperarConexion() {
        int elemConnected=0;
        try {
             //semilla = new Seeder();
            while (true) {
          Socket conexion = sock.accept(); // Crea objeto
           new manejadorConexion(conexion).start();
          if(conexion.isConnected()){
              System.out.println("se ha conectado alguien ... se esperan bytes");
              elemConnected++;
              System.out.println("Conectados : "+elemConnected);
          }
            }
            
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

    }
    

     



    public void ejecutarTracker() {
        try {
            sock = new ServerSocket(2722);

            System.out.println("Escucho el puerto " + 2722);
            esperarConexion();

        } catch (Exception ex) {
        }

    }






    public static void main(String args[]) {
        Tracker x = new Tracker();
        System.out.println("esperando una conexion");
        x.ejecutarTracker();
    }
}


class manejadorConexion extends Thread {
    private Socket socket;

    public manejadorConexion(Socket socket) {
        this.socket = socket;
    }


    private void monitorSeeder(SeederDetails x){
        System.out.println("SEEDER ubicado en : " + x.getHost());
        System.out.println("nombre del SEEDER : " + x.getNameSeeder());
        System.out.println("Enviar datagramas al puerto : " + x.getPortListenClient());
        System.out.println("status del SEEDER : " + x.getStatus());
        System.out.println("escucho al servidor desde el puerto : " + x.getPortListenTracker());
    }

    private boolean haveFile(String archivo, int portDgram, String address){
         boolean flag = false;
         byte[] buf = new  byte[1024];
         InetAddress x;
       
         System.out.println(archivo+" "+portDgram+" "+address);
         
        try {
            x = InetAddress.getByName(address);
            buf=archivo.getBytes();
            DatagramSocket datagram = new DatagramSocket(2726);
            DatagramPacket dp = new  DatagramPacket(buf, buf.length,x,2724);
           
            datagram.send(dp);

        } catch (SocketException ex) {
            Logger.getLogger(manejadorConexion.class.getName()).log(Level.SEVERE, null, ex);
        }catch (IOException ex) {
                Logger.getLogger(manejadorConexion.class.getName()).log(Level.SEVERE, null, ex);
        }
        return flag;
    }



    public void run() {
        try {
            //
            // leer mensaje del seeder
            //
           
        String nombArch = null;
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());            
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

//            Object objetoEntrada = ois.readObject();//recibo un objeto de alguna clase y verifico su procedencia
           
//                System.out.println(nombArch);
//                System.out.println("gracias cliente");
             Object obj = ois.readObject();

//          System.out.println(obj.toString()); prueba de que llega el obj desde el cliente
             
            if (obj instanceof SeederDetails) {
                SeederDetails x = (SeederDetails) obj;

               monitorSeeder(x);
                //
                // enviando respuesta al seeder
                //
                
                oos.writeObject("confirmado");


                ois.close();
                oos.close();
                socket.close();

                System.out.println("Esperando mas conexiones...");
            } else {
            if(obj instanceof String){
                nombArch=obj.toString();
                System.out.println(nombArch);
                haveFile(nombArch,2726,"localhost");
                }
            }
       
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(manejadorConexion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException e) {
            System.out.println("Servidor Tracker ha respondido al requestInfo de un cliente..." + e.getMessage());
            /*  e.printStackTrace();*/
        }
    }

    private String lookFileInSeedr(String fileName) {
    String fileNam= fileName;
    return fileNam;
    }
}
